package com.qst.itoffer.listener;

import jakarta.servlet.annotation.WebListener;
import jakarta.servlet.http.HttpSessionAttributeListener;
import jakarta.servlet.http.HttpSessionBindingEvent;
import jakarta.servlet.http.HttpSessionEvent;
import jakarta.servlet.http.HttpSessionListener;
import org.springframework.stereotype.Component;

import java.util.concurrent.ConcurrentHashMap;

@Component
@WebListener
public class OnlineUsersListener implements HttpSessionAttributeListener, HttpSessionListener {

    // 使用ConcurrentHashMap存储在线用户信息
    private ConcurrentHashMap<String, Object> onlineUsers = new ConcurrentHashMap<>();

    @Override
    public void attributeAdded(HttpSessionBindingEvent event) {
        if ("user".equals(event.getName())) {
            // 用户登录成功，将用户信息存入应用域
            onlineUsers.put(event.getSession().getId(), event.getValue());
        }
    }

    @Override
    public void attributeRemoved(HttpSessionBindingEvent event) {
        if ("user".equals(event.getName())) {
            // 用户退出，移除用户信息
            onlineUsers.remove(event.getSession().getId());
        }
    }

    @Override
    public void sessionCreated(HttpSessionEvent se) {
        // 会话创建时的操作
    }

    @Override
    public void sessionDestroyed(HttpSessionEvent se) {
        // 会话销毁时的操作
        onlineUsers.remove(se.getSession().getId());
    }

    public ConcurrentHashMap<String, Object> getOnlineUsers() {
        return onlineUsers;
    }
}